//
//  BVAddAddressViewController.m
//  BuyVegetables
//
//  Created by 叶思超 on 15/10/13.
//  Copyright (c) 2015年 叶思超. All rights reserved.
//

#import "BVAddAddressViewController.h"
#import "BVConst.h"
#import "UIView+Extension.h"
#import "NSString+Extension.h"
#import "HttpTool.h"
#import "BVBMKMapViewController.h"
#import <BaiduMapAPI/BMapKit.h>
#import "MBProgressHUD+MJ.h"
#import "AppDelegate.h"
#import "BVLoginViewController.h"

#import "HttpTool.h"
#import "BVBusinessModelNSObject.h"
#import "BVBusinessModelData.h"
@interface BVAddAddressViewController () <BVBMKMapViewControllerDelegate, UITextFieldDelegate,UIPickerViewDataSource, UIPickerViewDelegate>
/**
 *  姓名
 */
@property (nonatomic, strong) UITextField *nameF;
/**
 *  手机号
 */
@property (nonatomic, strong) UITextField *phoneF;
/**
 *  地址
 */
@property (nonatomic, strong) UITextField *addressF;
/**
 *  详细地址
 */
@property (nonatomic, strong) UITextField *detailAddressF;

/**
 *  创建pickView
 */
@property (nonatomic, strong) UIPickerView *BusinessPickerView;
/**
 *  商圈
 */
@property (nonatomic ,strong) UITextField * BusinessF;


/**
 *  商圈button
 */
@property (nonatomic ,strong) UIButton * BusinessFB;


/**
 *  商圈选择父视图
 */
@property (nonatomic, strong) UIView *citySelected;
/**
 *  存放所有商圈信息
 */
@property (nonatomic, strong) NSMutableArray *BusinessArry;
/**
 *  商圈ID
 */
@property (nonatomic,   copy)NSString * SID;

@end

@implementation BVAddAddressViewController

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    [self.addressF resignFirstResponder];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.nameF becomeFirstResponder];
    
//    //请求商圈内容
    [self getShangQuan];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置导航栏
    [self setupNav];
    
    // 设置UI
    [self setupUI];
    
    //注册键盘出现的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cancelBtnClick) name:UIKeyboardWillShowNotification object:nil];
}

#pragma mark -- 设置UI
- (void)setupUI {
    // 联系人标签
    UILabel *contactLabel = [[UILabel alloc] init];
    contactLabel.frame = CGRectMake(10, 84, 75, 40);
    contactLabel.backgroundColor = [UIColor whiteColor];
    contactLabel.font = [UIFont systemFontOfSize:15];
    contactLabel.text = @"联 系 人:";
    contactLabel.textAlignment = NSTextAlignmentCenter;
    contactLabel.textColor = BVBaseTextBlackColor;
    [self.view addSubview:contactLabel];
    
    // 联系人姓名
    self.nameF = [[UITextField alloc] init];
    self.nameF.frame = CGRectMake(85, contactLabel.y , BVScreenW - CGRectGetMaxX(contactLabel.frame) - 10, 40);
    self.nameF.placeholder = @"您的姓名";
    self.nameF.font = [UIFont systemFontOfSize:15];
    self.nameF.backgroundColor = [UIColor whiteColor];
    self.nameF.textColor = BVBaseTextBlackColor;
    [self.view addSubview:self.nameF];
    
    // 分割线一
    UIView *oneSeparatorLine = [[UIView alloc] init];
    oneSeparatorLine.frame = CGRectMake(10, CGRectGetMaxY(contactLabel.frame), BVScreenW - 2 * 10, 0.7);
    oneSeparatorLine.backgroundColor = BVTextLightGrayColor;
    [self.view addSubview:oneSeparatorLine];
    
    // 联系方式标签
    UILabel *telLabel = [[UILabel alloc] init];
    telLabel.frame = CGRectMake(10, CGRectGetMaxY(oneSeparatorLine.frame), 75, 40);
    telLabel.font = [UIFont systemFontOfSize:15];
    telLabel.text = @"联系方式:";
    telLabel.textColor = BVBaseTextBlackColor;
    telLabel.textAlignment = NSTextAlignmentCenter;
    telLabel.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:telLabel];
    
    // 联系方式
    self.phoneF = [[UITextField alloc] init];
    self.phoneF.frame = CGRectMake(CGRectGetMaxX(telLabel.frame), telLabel.y, BVScreenW - CGRectGetMaxX(telLabel.frame) - 10, 40);
    self.phoneF.delegate = self;
    self.phoneF.placeholder = @"您的手机号";
    self.phoneF.backgroundColor = [UIColor whiteColor];
    self.phoneF.textColor = BVBaseTextBlackColor;
    self.phoneF.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:self.phoneF];
    
    // 分割线二
    UIView *twoSeparatorLine = [[UIView alloc] init];
    twoSeparatorLine.frame = CGRectMake(10, CGRectGetMaxY(self.phoneF.frame), BVScreenW - 2 * 10, 0.5);
    twoSeparatorLine.backgroundColor = BVTextLightGrayColor;
    [self.view addSubview:twoSeparatorLine];

    // 收货地址标签
    UILabel *addressLabel = [[UILabel alloc] init];
    addressLabel.frame = CGRectMake(10, CGRectGetMaxY(twoSeparatorLine.frame), 75, 40);
    addressLabel.textColor = BVBaseTextBlackColor;
    addressLabel.backgroundColor = [UIColor whiteColor];
    addressLabel.text = @"收货地址:";
    addressLabel.textAlignment = NSTextAlignmentCenter;
    addressLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:addressLabel];
    
    // 获取收货地址
    self.addressF = [[UITextField alloc] init];
    self.addressF.frame = CGRectMake(CGRectGetMaxX(addressLabel.frame), addressLabel.y, BVScreenW - CGRectGetMaxX(addressLabel.frame) - 10, 40);
    self.addressF.placeholder = @"小区/写字楼/学校";
    self.addressF.delegate = self;
    self.addressF.backgroundColor = [UIColor whiteColor];
    self.addressF.font = [UIFont systemFontOfSize:15];
    self.addressF.textColor = BVBaseTextBlackColor;
    [self.view addSubview:self.addressF];
    
    // 分割线三
    UIView *threSeparatorLine = [[UIView alloc] init];
    threSeparatorLine.frame = CGRectMake(10, CGRectGetMaxY(self.addressF.frame), BVScreenW - 2 * 10, 0.5);
    threSeparatorLine.backgroundColor = BVTextLightGrayColor;
    [self.view addSubview:threSeparatorLine];
    
    // 详细地址Label
    UILabel *detailLabel = [[UILabel alloc] init];
    detailLabel.frame = CGRectMake(10, CGRectGetMaxY(threSeparatorLine.frame), 75, 40);
    detailLabel.font = [UIFont systemFontOfSize:15];
    detailLabel.backgroundColor = [UIColor whiteColor];
    detailLabel.textColor = BVBaseTextBlackColor;
    detailLabel.text = @"详细地址:";
    detailLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:detailLabel];
    
    // 详细地址
    self.detailAddressF = [[UITextField alloc] init];
    self.detailAddressF.frame = CGRectMake(CGRectGetMaxX(telLabel.frame), CGRectGetMaxY(threSeparatorLine.frame), BVScreenW - CGRectGetMaxX(telLabel.frame) - 10, 40);
    self.detailAddressF.placeholder = @"详细地址(如门牌号等)";
    self.detailAddressF.backgroundColor = [UIColor whiteColor];
    [self.detailAddressF setValue:[UIFont systemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
    self.detailAddressF.textColor = BVBaseTextBlackColor;
    [self.view addSubview:self.detailAddressF];
    
    // 分割线六
    UIView *sixSeparatorLine = [[UIView alloc] init];
    sixSeparatorLine.frame = CGRectMake(10, CGRectGetMaxY(self.detailAddressF.frame), BVScreenW - 2 * 10, 0.5);
    sixSeparatorLine.backgroundColor = BVTextLightGrayColor;
    [self.view addSubview:sixSeparatorLine];
    
    // 分割线四
    UIView *fourSeparatorLine = [[UIView alloc] init];
    fourSeparatorLine.frame = CGRectMake(10, CGRectGetMaxY(threSeparatorLine.frame) + 40, BVScreenW - 2 * 10, 0.5);
    fourSeparatorLine.backgroundColor = BVTextLightGrayColor;
    [self.view addSubview:fourSeparatorLine];
    
    
    //商圈选择标签
    UILabel * BusinessCircle = [[UILabel alloc]init];
    BusinessCircle.frame = CGRectMake(10, CGRectGetMaxY(fourSeparatorLine.frame), 75, 40);
    BusinessCircle.text = @"商       圈:";
    BusinessCircle.textColor = BVBaseTextBlackColor;
    BusinessCircle.backgroundColor = [UIColor whiteColor];
    BusinessCircle.font = [UIFont systemFontOfSize:15];
    BusinessCircle.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:BusinessCircle];
    
    //商圈textField
    self.BusinessFB = [[UIButton alloc]init];
    [self.BusinessFB setTitle:@"请选择商圈" forState:UIControlStateNormal];
    self.BusinessFB.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
    self.BusinessFB.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.BusinessFB setTitleColor:BVBaseTextBlackColor forState:UIControlStateNormal];
    self.BusinessFB.backgroundColor = [UIColor whiteColor];
    self.BusinessFB.frame = CGRectMake(CGRectGetMaxX(BusinessCircle.frame), BusinessCircle.y, BVScreenW - CGRectGetMaxX(addressLabel.frame) - 10, 40);
    [self.BusinessFB addTarget:self action:@selector(seten) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.BusinessFB];
    
    UIView *fifthSeparatorLine = [[UIView alloc] init];
    fourSeparatorLine.frame = CGRectMake(10, CGRectGetMaxY(fourSeparatorLine.frame) + 40, BVScreenW - 2 * 10, 0.5);
    fourSeparatorLine.backgroundColor = BVTextLightGrayColor;
    [self.view addSubview:fifthSeparatorLine];

    // 确定添加
    UIButton *confirmButton = [[UIButton alloc] init];
    confirmButton.frame = CGRectMake(10, CGRectGetMaxY(BusinessCircle.frame) + 50, BVScreenW - 2 * 10, 40);
    confirmButton.backgroundColor = BVBaseOrangeColor;
    confirmButton.titleLabel.font = [UIFont systemFontOfSize:20];
    [confirmButton setTitle:@"确  定" forState:UIControlStateNormal];
    [confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmButton addTarget:self action:@selector(confirmButtonClick) forControlEvents:UIControlEventTouchUpInside];
    confirmButton.layer.masksToBounds = YES;
    confirmButton.layer.cornerRadius = 4;
    [self.view addSubview:confirmButton];
}
-(void)seten{
    [self.view endEditing:YES];
    
    [self setpick];
}
#pragma mark -- UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (self.addressF == textField) {
        BVBMKMapViewController *bmkMapVC = [[BVBMKMapViewController alloc] init];
        bmkMapVC.delegate = self;
        ROOTNAVPUSH(bmkMapVC, YES);
        
    }
}

#pragma mark - 判断手机号是否合法
- (BOOL)isMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[0-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[0-8])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

#pragma mark --  button点击事件
- (void)confirmButtonClick {
    // 拼接路径
    NSString *url = [NSString stringWithFormat:@"%@/VegetableUserAPI/doUserAddAressById", Path];
    
    // 拼接参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *userinfo = [defaults dictionaryForKey:@"USERINFO"];
    NSString *user_id = userinfo[@"id"];
    if (user_id != nil) {
        params[@"user_id"] = user_id;
        if (self.nameF.text.length == 0) {
            [MBProgressHUD showError:@"请填写联系人" toView:self.view];
        } else {
            params[@"contact"] = self.nameF.text;
            if ([self isMobileNumber:self.phoneF.text] == NO) {
                [MBProgressHUD showError:@"电话号码非法,请重新输入" toView:self.view];
            } else {
                params[@"mobile"] = self.phoneF.text;
                if (self.addressF.text.length == 0) {
                    [MBProgressHUD showError:@"请填写地址" toView:self.view];
                } else {
                    params[@"receive_address"] = self.addressF.text;
                    if (self.detailAddressF.text.length == 0) {
                        [MBProgressHUD showError:@"请填写详细地址" toView:self.view];
                    } else {
                        params[@"detailed_address"] = self.detailAddressF.text;
                        
                        if ([self.BusinessFB.titleLabel.text isEqualToString:@"请选择商圈"]) {
                            
                            [MBProgressHUD showError:@"请选择商圈" toView:self.view];
                            
                        }else{
                
                             params[@"trade_id"] = self.SID;
                            
                            [HttpTool get:url params:params success:^(id responseObj) {
                                if ([responseObj[@"code"] isEqualToString:@"1"]) {
                                    BVLog(@"添加新地址成功-----%@", responseObj);
                                    if ([self.delegate respondsToSelector:@selector(addAddressDidFinish:)]) {
                                        [self.delegate addAddressDidFinish:self];
                                        ROOTNAVPOP
                                    }
                                } else {
                                    BVLog(@"添加新地址失败-----%@", responseObj);
                                }
                            } failure:^(NSError *error) {
                                BVLog(@"请求失败-----%@", error);
                            }];

                    }
                    
                    
                    }
                }
            }
        }
    } else  {
        
    }
}

#pragma mark -- BVBMKMapViewControllerDelegate
- (void)mapViewController:(BVBMKMapViewController *)bmkMap poiInfo:(BMKPoiInfo *)poiInfo {
    // 设置收获地址
    self.addressF.text = poiInfo.name;
    // 设置收货详细地址
//    self.detailAddressF.text = poiInfo.address;
    [self.detailAddressF becomeFirstResponder];
}


#pragma mark -- 设置商圈pick
-(void)setpick{
    
    if(_citySelected) return;
    
    _citySelected = [[UIView alloc] init];
    _citySelected.frame = CGRectMake(0, BVScreenH - 261, BVScreenW, 261);
    _citySelected.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_citySelected];
    
    // 1.创建pickView
    UIPickerView *pickerView  = [[UIPickerView alloc] init];
    pickerView.y = _citySelected.height - 216;
    pickerView.width = BVScreenW;
    pickerView.delegate = self;
    pickerView.dataSource = self;
    [_citySelected addSubview:pickerView];

    self.BusinessPickerView = pickerView;

    // 2.添加工具条
    UIView *toolView = [[UIView alloc] init];
    toolView.frame = CGRectMake(0, 0, BVScreenW, 45);
    toolView.backgroundColor = BVBackgroundLightGrayColor;
    [_citySelected addSubview:toolView];
    
    UIButton *cancelButton = [[UIButton alloc] init];
    cancelButton.frame = CGRectMake(0, 0, 60, 45);
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setTitleColor:BVBaseOrangeColor forState:UIControlStateNormal];
    cancelButton.titleLabel.font  = [UIFont systemFontOfSize:15];
    [cancelButton addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [toolView addSubview:cancelButton];
    
    UIButton *correctButton = [[UIButton alloc] init];
    correctButton.frame = CGRectMake(BVScreenW - 60, 0, 60, 45);
    [correctButton setTitle:@"确定" forState:UIControlStateNormal];
    [correctButton setTitleColor:BVBaseOrangeColor forState:UIControlStateNormal];
    correctButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [correctButton addTarget:self action:@selector(corretButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [toolView addSubview:correctButton];

    
}
/**
 *隐藏pick
 */
- (void)cancelBtnClick {
    
    [self.citySelected removeFromSuperview];
    self.citySelected = nil;
    [self.BusinessF resignFirstResponder];

}
/*
    将pick的选中赋值
 
 */
- (void)corretButtonClick {

    // 返回拨键盘时被选定的行
    NSInteger row1 = [self.BusinessPickerView selectedRowInComponent:0];
    
    BVBusinessModelData * ModelData = self.BusinessArry[row1];
    
    // 获得选中的商圈
    NSString *proviceName = ModelData.title;
    
    //self.BusinessF.text = proviceName;
    
    [self.BusinessFB setTitle:proviceName forState:UIControlStateNormal];
    
    self.SID = ModelData.dataIdentifier;
    
    
    // 移除pickerView
    [self.citySelected removeFromSuperview];
    self.citySelected = nil;
    [self.BusinessF resignFirstResponder];
}
// 告诉系统有多少列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    
    return 1;
}
// 告诉系统有多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
   
    if (!_BusinessArry){
    //
    }
    return self.BusinessArry.count;
    
}
#pragma mark - UIPickerViewDelegate
// 告诉系统每一行显示什么内容
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    
    BVBusinessModelData * ModelData = self.BusinessArry[row];
    
    return ModelData.title;
}

//获取商圈内容
-(void)getShangQuan{
    
    self.BusinessArry = [[NSMutableArray alloc]init];
    NSString * city =  [[NSUserDefaults standardUserDefaults]objectForKey:@"city"];
    NSString *url = [NSString stringWithFormat:@"%@/VegetableUserAPI/businesscircle?city=%@", Path,city];
    NSString *dataUTF8 = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    BVLog(@"这是拼接好的url=======%@",url);
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [HttpTool get:dataUTF8 params:params success:^(id responseObj) {
        BVBusinessModelNSObject * NsObj = [BVBusinessModelNSObject modelObjectWithDictionary:responseObj];;
        
        for (BVBusinessModelData * ModelData in NsObj.data) {
            [self.BusinessArry addObject:ModelData];
        }
    } failure:^(NSError *error) {
        BVLog(@"请求失败");
    }];
    
    
}
#pragma mark -- 设置导航栏
- (void)setupNav {
    
    self.title = @"新增地址";
    self.navigationController.navigationBar.barTintColor = BVBaseOrangeColor;
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(backClick)];
}

#pragma mark -- 返回
- (void)backClick {
    ROOTNAVPOP
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
    [self.view endEditing:YES];
}
@end
